package com.newlink.building.notifications

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.NL_App.Companion.ensureCoreExists
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.tools.Log

/**
 * Created by xiaodong on 2022/9/20.
 */
class Module_Phone_NotificationBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.i("[Notification Broadcast Receiver] Ensuring Core exists")
        ensureCoreExists(context, false)

        val notificationId = intent.getIntExtra(NotificationsManager.INTENT_NOTIF_ID, 0)
        Log.i("[Notification Broadcast Receiver] Got notification broadcast for ID [$notificationId]")

        if (intent.action == NotificationsManager.INTENT_ANSWER_CALL_NOTIF_ACTION || intent.action == NotificationsManager.INTENT_HANGUP_CALL_NOTIF_ACTION) {
            handleCallIntent(intent)
        }
    }

    private fun handleCallIntent(intent: Intent) {
        val remoteSipAddress = intent.getStringExtra(NotificationsManager.INTENT_REMOTE_ADDRESS)
        if (remoteSipAddress == null) {
            Log.e("[Notification Broadcast Receiver] Remote SIP address is null for notification")
            return
        }

        val core: Core = coreContext.core

        val remoteAddress = core.interpretUrl(remoteSipAddress)
        val call = if (remoteAddress != null) core.getCallByRemoteAddress2(remoteAddress) else null
        if (call == null) {
            Log.e("[Notification Broadcast Receiver] Couldn't find call from remote address $remoteSipAddress")
            return
        }

        if (intent.action == NotificationsManager.INTENT_ANSWER_CALL_NOTIF_ACTION) {
            coreContext.answerCall(call)
        } else {
            if (call.state == Call.State.IncomingReceived ||
                call.state == Call.State.IncomingEarlyMedia
            ) {
                coreContext.declineCall(call)
            } else {
                coreContext.terminateCall(call)
            }
        }
    }
}